﻿using System.ComponentModel;
using Kingdee.BOS;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;

namespace Caraya.MFG.BusinessPlugIn
{
    /// <summary>
    /// 操作服务插件
    /// </summary>
    [Description("入库审核测试"), HotUpdate]
    public class InStockAudit : Kingdee.BOS.Core.DynamicForm.PlugIn.AbstractOperationServicePlugIn
    {
        public override void BeginOperationTransaction(Kingdee.BOS.Core.DynamicForm.PlugIn.Args.BeginOperationTransactionArgs e)
        {
            long lgPrdOrgId = this.Context.CurrentOrganizationInfo.ID;
            //acctBookId为账簿Id
            var config = SystemParameterServiceHelper.Load(this.Context, lgPrdOrgId, 0, "MFG_ProducutonParameter");
            _ = bool.TryParse(config["F_CARA_CheckMr"]?.ToString(), out bool IsCheckMr);
            //var IsCheckMr = MFGServiceHelper.GetSystemProfile<bool>(base.Context, lgPrdOrgId, "MFG_ProducutonParameter", "F_CARA_CheckMr", false);
            if (IsCheckMr)
            {
                var errTxt = "";
                foreach (var model in e.DataEntitys)
                {
                    DynamicObjectCollection entity = model["Entity"] as DynamicObjectCollection;
                    foreach (var obj in entity)
                    {
                        var fid = obj["MoEntryId"];
                        var seq = obj["Seq"];
                        var RealQty = obj["BasePrdRealQty"].ToString();

                        var sql = "SELECT t2.FPICKMTLQTY - t1.FQTY + t2.FNOSTOCKINQTY AS e0 FROM T_PRD_MOENTRY AS t1 LEFT OUTER JOIN T_PRD_MOENTRY_Q AS t2 ON t1.FENTRYID = t2.FENTRYID WHERE t1.FENTRYID = " + fid.ToString();
                        var pickMtrlQty = DBServiceHelper.ExecuteScalar<double>(this.Context, sql, 0d);
                        if (pickMtrlQty < double.Parse(RealQty))
                        {
                            errTxt += "第" + seq.ToString() + "行 领料套数 " + pickMtrlQty.ToString() + " 小于实收数量 " + RealQty.ToString() + "\n";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(errTxt))
                {
                    errTxt += "请联系车间领料人员 确认是否全部领料！\n\n";
                    throw new KDException("100001", "领料异常：\n" + errTxt);
                }
            }
            base.BeginOperationTransaction(e);
        }
    }
}
